import LoadManager from "../../manager/LoadManager";
import LoginModel from "../../model/LoginModel";
import SceneManager from "../../manager/SceneManager";

const {ccclass, property} = cc._decorator;

@ccclass
export default class CreateUserView extends cc.Component {

    @property(cc.Button)
    btn_random: cc.Button = null;
    @property(cc.Button)
    btn_male: cc.Button = null;
    @property(cc.Button)
    btn_female: cc.Button = null;
    @property(cc.Button)
    btn_ok: cc.Button = null;

    @property(cc.Node)
    avatar: cc.Node = null;
    @property(cc.Label)
    txt_sex:cc.Label = null;
    @property(cc.Label)
    txt_atk:cc.Label = null;
    @property(cc.Label)
    txt_def:cc.Label = null;
    @property(cc.Label)
    txt_hp:cc.Label = null;
    @property(cc.Label)
    txt_mp:cc.Label = null;
    @property(cc.EditBox)
    editbox_username:cc.EditBox = null;
    private onSetHeroInfo(heroObj:object) {
        let heroCfg:Array<object> = LoadManager.instance.getStaticConfigResByUrl("config/HeroConfig")
        let temp:object = heroCfg[heroObj["id"]]
        let id:string = String(temp["avatarId"])
        let len:number = 4-id.length
        for (let index = 0; index < len; index++) {
            id = "0"+id
        }
        this.avatar.getComponent(sp.Skeleton).skeletonData = LoadManager.instance.getSkeletonDataByUrl("spine/character/r_"+id)
        this.avatar.getComponent(sp.Skeleton).setAnimation(0,"idle",true)
        this.txt_atk.string = "攻击:"+heroObj["atk"]
        this.txt_def.string = "防御:"+heroObj["def"]
        this.txt_hp.string = "血量:"+heroObj["hp"]
        this.txt_mp.string = "魔法:"+heroObj["mp"]
    }
    private onRandomPerson() {
        LoginModel.instance.actionRandomHero(this.onSetHeroInfo.bind(this))
    }
    private sex:number = 0
    private onSelectSex(event:cc.Event.EventTouch) {
        this.sex = 0
        if (event.target==this.btn_male.node)
        {
            this.sex = 0
        }
        if (event.target==this.btn_female.node)
        {
            this.sex = 1
        }
        this.txt_sex.string = (this.sex==0)&&"性别:男"||"性别:女"
    }
    private onOk() {
        LoginModel.instance.actionCreateUser(this.editbox_username.string,this.sex,function(){
            SceneManager.instance.goto("MainScene")
        }.bind(this))
    }
    start () {
        this.btn_random.node.on(cc.Node.EventType.TOUCH_END,this.onRandomPerson,this)
        this.btn_male.node.on(cc.Node.EventType.TOUCH_END,this.onSelectSex,this)
        this.btn_female.node.on(cc.Node.EventType.TOUCH_END,this.onSelectSex,this)
        this.btn_ok.node.on(cc.Node.EventType.TOUCH_END,this.onOk,this)
        this.onRandomPerson()
    }

}
